package com.rr.middle;

import java.util.*;

/**
 * https://leetcode.cn/problems/combination-sum/description/?envType=daily-question&envId=2024-04-20
 */
public class CombinationSum {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList<>();
        getResult(candidates, target, result, new ArrayList<>(), 0, candidates.length);
//        return distinct(result);
        return result;
    }

    private void getResult(int[] candidates, int target, List<List<Integer>> result, List<Integer> current,int left, int right) {
        for (int i = left; i < right; i++) {
            int restTarget = target - candidates[i];
            if (restTarget > 0) {
                List<Integer> newCurrent = new ArrayList<>(current);
                newCurrent.add(candidates[i]);
                getResult(candidates, restTarget, result, newCurrent, i, right);
            } else if (restTarget == 0) {
                List<Integer> newCurrent = new ArrayList<>(current);
                newCurrent.add(candidates[i]);
                result.add(newCurrent);
                break;
            }
        }
    }

    private List<List<Integer>> distinct(List<List<Integer>> result) {
        List<List<Integer>> distinctResult = new ArrayList<>();
        Set<String> set = new HashSet<>();
        for (List<Integer> list : result) {
            list.sort(Integer::compareTo);
            if (set.add(list.toString())) {
                distinctResult.add(list);
            }
        }
        return distinctResult;
    }

    public static void main(String[] args) {
        CombinationSum combinationSum = new CombinationSum();
        List<List<Integer>> lists = combinationSum.combinationSum(new int[] {2, 3, 7}, 18);
        System.out.println(lists);
    }
}
